package com.ruoyi.web.controller.app;


import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.system.domain.SysOss;
import com.ruoyi.system.service.ISysOssService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

@RequiredArgsConstructor
@RestController
@RequestMapping("/app/upload")
public class AppUploadController extends BaseController {

    private final ISysOssService iSysOssService;

    /**
     * 上传文件图片视频
     *
     * @param file 文件信息
     * @return
     */
    @PostMapping(value = "oss", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public R<Map<String, String>> upload(@RequestPart("file") MultipartFile file) {
        if (ObjectUtil.isNull(file)) {
            throw new ServiceException("上传文件不能为空");
        }
        SysOss oss = iSysOssService.upload(file);
        Map<String, String> map = new HashMap<>(2);
        map.put("url", oss.getUrl());
        map.put("fileName", oss.getOriginalName());
        map.put("ossId", oss.getOssId().toString());
        return R.ok(map);
    }

    /**
     * 上传文件图片视频
     *
     * @param file 文件信息
     * @return
     */
    @PostMapping(value = "fileOss", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public R<Object> fileUploads(MultipartFile[] file) {
        if (ObjectUtil.isNull(file) && file.length > 0) {
            throw new ServiceException("上传文件不能为空");
        }
        ArrayList<Map<String, String>> data = new ArrayList<>();
        for (int i = 0; i < file.length; i++) {
            SysOss oss = iSysOssService.upload(file[i]);
            Map<String, String> map = new HashMap<>(2);
            map.put("url", oss.getUrl());
            map.put("fileName", oss.getOriginalName());
            map.put("ossId", oss.getOssId().toString());
            data.add(map);
        }
        return R.ok(data);
    }

}
